<template>
    <!-- AI助手悬浮按钮 -->
    <div class="fixed bottom-6 right-6 z-50">
        <!-- 聊天按钮 -->
        <button 
            @click="toggleChat" 
            class="bg-gradient-to-r from-blue-500 to-purple-600 hover:from-blue-600 hover:to-purple-700 
                   text-white rounded-full p-4 shadow-lg hover:shadow-xl transition-all duration-300
                   flex items-center justify-center group"
            :class="{ 'animate-pulse': !isChatOpen }"
        >
            <!-- AI图标 -->
            <svg v-if="!isChatOpen" class="w-6 h-6" fill="currentColor" viewBox="0 0 24 24">
                <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
            </svg>
            <!-- 关闭图标 -->
            <svg v-else class="w-6 h-6" fill="currentColor" viewBox="0 0 24 24">
                <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
            </svg>
        </button>

        <!-- 聊天窗口 -->
        <transition name="slide-up">
            <div v-if="isChatOpen" 
                 class="absolute bottom-16 right-0 w-96 h-96 bg-white rounded-lg shadow-2xl border border-gray-200 
                        dark:bg-gray-800 dark:border-gray-700 flex flex-col overflow-hidden">
                
                <!-- 聊天头部 -->
                <div class="bg-gradient-to-r from-blue-500 to-purple-600 text-white p-4 flex items-center justify-between">
                    <div class="flex items-center space-x-2">
                        <div class="w-8 h-8 bg-white/20 rounded-full flex items-center justify-center">
                            <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
                                <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
                            </svg>
                        </div>
                        <div>
                            <h3 class="font-semibold text-sm">AI助手</h3>
                            <p class="text-xs opacity-80">{{ currentConversationTitle }}</p>
                        </div>
                    </div>
                    <div class="flex items-center space-x-2">
                        <!-- 对话列表按钮 -->
                        <button @click="toggleConversationList"
                                class="text-white/80 hover:text-white p-1 rounded transition-colors"
                                title="对话列表">
                            <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
                                <path d="M3,6H21V8H3V6M3,11H21V13H3V11M3,16H21V18H3V16Z"/>
                            </svg>
                        </button>
                        <!-- 新对话按钮 -->
                        <button @click="startNewConversation"
                                class="text-white/80 hover:text-white p-1 rounded transition-colors"
                                title="新对话"
                                :disabled="isLoading">
                            <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
                                <path d="M19,13H13V19H11V13H5V11H11V5H13V11H19V13Z"/>
                            </svg>
                        </button>
                        <!-- 加载历史记录按钮 -->
                        <button v-if="conversationId"
                                @click="loadChatHistory"
                                class="text-white/80 hover:text-white p-1 rounded transition-colors"
                                title="加载历史记录"
                                :disabled="isLoading">
                            <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
                                <path d="M13,3A9,9 0 0,0 4,12H1L4.89,15.89L4.96,16.03L9,12H6A7,7 0 0,1 13,5A7,7 0 0,1 20,12A7,7 0 0,1 13,19C11.07,19 9.32,18.21 8.06,16.94L6.64,18.36C8.27,20 10.5,21 13,21A9,9 0 0,0 22,12A9,9 0 0,0 13,3Z"/>
                            </svg>
                        </button>
                        <!-- 清空对话按钮 -->
                        <button @click="clearConversation"
                                class="text-white/80 hover:text-white p-1 rounded transition-colors"
                                title="清空对话">
                            <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
                                <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>
                            </svg>
                        </button>
                    </div>
                </div>

                <!-- 聊天消息区域 -->
                <div class="flex-1 overflow-y-auto p-4 space-y-3" ref="messagesContainer">
                    <!-- 欢迎消息 -->
                    <div v-if="messages.length === 0" class="text-center text-gray-500 dark:text-gray-400 py-8">
                        <div class="mb-4">
                            <svg class="w-12 h-12 mx-auto text-gray-300 dark:text-gray-600" fill="currentColor" viewBox="0 0 24 24">
                                <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
                            </svg>
                        </div>
                        <p class="text-sm">你好！我是AI助手</p>
                        <p class="text-xs mt-1">有什么技术问题可以问我哦~</p>
                    </div>

                    <!-- 消息列表 -->
                    <div v-for="(message, index) in messages" :key="index" 
                         class="flex" :class="{ 'justify-end': message.isUser }">
                        <div class="max-w-xs lg:max-w-md px-3 py-2 rounded-lg text-sm"
                             :class="message.isUser 
                                ? 'bg-blue-500 text-white rounded-br-none' 
                                : 'bg-gray-100 dark:bg-gray-700 text-gray-900 dark:text-white rounded-bl-none'">
                            
                            <!-- 用户消息 -->
                            <div v-if="message.isUser" class="whitespace-pre-line">{{ message.content }}</div>
                            
                            <!-- AI消息（富文本显示） -->
                            <div v-else>
                                <div class="markdown-content prose prose-sm max-w-none" 
                                     v-html="renderMarkdown(message.content)"></div>
                                
                                <!-- 推荐文章 -->
                                <div v-if="message.recommendArticles && message.recommendArticles.length > 0" 
                                     class="mt-3 space-y-2">
                                    <p class="text-xs font-semibold text-gray-600 dark:text-gray-300">推荐文章：</p>
                                    <div v-for="article in message.recommendArticles" :key="article.id"
                                         class="bg-white/10 rounded p-2 cursor-pointer hover:bg-white/20 transition-colors"
                                         @click="goToArticle(article.id)">
                                        <p class="font-medium text-xs line-clamp-1">{{ article.title }}</p>
                                        <p class="text-xs opacity-80 mt-1 line-clamp-2">{{ article.summary }}</p>
                                        <p class="text-xs opacity-60 mt-1">{{ article.createTime }}</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 输入中状态 -->
                    <div v-if="isTyping" class="flex">
                        <div class="bg-gray-100 dark:bg-gray-700 px-3 py-2 rounded-lg rounded-bl-none">
                            <div class="flex space-x-1">
                                <div class="w-2 h-2 bg-gray-400 rounded-full animate-bounce"></div>
                                <div class="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style="animation-delay: 0.1s"></div>
                                <div class="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style="animation-delay: 0.2s"></div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 输入区域 -->
                <div class="border-t border-gray-200 dark:border-gray-600 p-3">
                    <div class="flex space-x-2">
                        <input 
                            v-model="inputMessage" 
                            @keyup.enter="sendMessage"
                            placeholder="输入你的问题..."
                            class="flex-1 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg 
                                   text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 
                                   dark:bg-gray-700 dark:text-white"
                            :disabled="isTyping"
                        />
                        <button 
                            @click="sendMessage" 
                            :disabled="!inputMessage.trim() || isTyping"
                            class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 
                                   disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                        >
                            <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
                                <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
                            </svg>
                        </button>
                    </div>
                </div>
            </div>
        </transition>

        <!-- 对话列表侧边栏 -->
        <transition name="slide-left">
            <div v-if="showConversationList && isChatOpen"
                 class="absolute bottom-16 right-96 w-80 h-96 bg-white rounded-lg shadow-2xl border border-gray-200
                        dark:bg-gray-800 dark:border-gray-700 flex flex-col overflow-hidden ml-4">

                <!-- 对话列表头部 -->
                <div class="bg-gradient-to-r from-purple-500 to-pink-600 text-white p-4 flex items-center justify-between">
                    <div class="flex items-center space-x-2">
                        <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
                            <path d="M3,6H21V8H3V6M3,11H21V13H3V11M3,16H21V18H3V16Z"/>
                        </svg>
                        <h3 class="font-semibold text-sm">对话列表</h3>
                    </div>
                    <button @click="showConversationList = false"
                            class="text-white/80 hover:text-white p-1 rounded transition-colors">
                        <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
                            <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
                        </svg>
                    </button>
                </div>

                <!-- 对话列表内容 -->
                <div class="flex-1 overflow-y-auto p-3">
                    <!-- 加载状态 -->
                    <div v-if="isLoading" class="text-center py-8">
                        <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-500 mx-auto"></div>
                        <p class="text-sm text-gray-500 dark:text-gray-400 mt-2">加载中...</p>
                    </div>

                    <!-- 空状态 -->
                    <div v-else-if="conversationList.length === 0" class="text-center py-8">
                        <svg class="w-12 h-12 mx-auto text-gray-300 dark:text-gray-600 mb-4" fill="currentColor" viewBox="0 0 24 24">
                            <path d="M20,2H4A2,2 0 0,0 2,4V22L6,18H20A2,2 0 0,0 22,16V4A2,2 0 0,0 20,2Z"/>
                        </svg>
                        <p class="text-sm text-gray-500 dark:text-gray-400">暂无对话记录</p>
                        <p class="text-xs text-gray-400 dark:text-gray-500 mt-1">开始新对话吧！</p>
                    </div>

                    <!-- 对话列表 -->
                    <div v-else class="space-y-2">
                        <div v-for="conversation in conversationList" :key="conversation.conversationId"
                             class="p-3 rounded-lg transition-colors hover:bg-gray-100 dark:hover:bg-gray-700 group"
                             :class="{ 'bg-purple-50 dark:bg-purple-900/20 border border-purple-200 dark:border-purple-700': conversation.conversationId === conversationId }">
                            <div class="flex items-start justify-between">
                                <div class="flex-1 min-w-0 cursor-pointer" @click="switchConversation(conversation)">
                                    <h4 class="font-medium text-sm text-gray-900 dark:text-white truncate">
                                        {{ conversation.title }}
                                    </h4>
                                    <p class="text-xs text-gray-500 dark:text-gray-400 mt-1 line-clamp-2">
                                        {{ conversation.lastMessage }}
                                    </p>
                                    <div class="flex items-center justify-between mt-2">
                                        <span class="text-xs text-gray-400 dark:text-gray-500">
                                            {{ formatTime(conversation.lastUpdateTime) }}
                                        </span>
                                        <span class="text-xs bg-gray-200 dark:bg-gray-600 text-gray-600 dark:text-gray-300 px-2 py-1 rounded-full">
                                            {{ conversation.messageCount }}条
                                        </span>
                                    </div>
                                </div>
                                <!-- 删除按钮 -->
                                <div class="ml-2 opacity-0 group-hover:opacity-100 transition-opacity">
                                    <button @click.stop="deleteConversationConfirm(conversation)"
                                            :disabled="isLoading"
                                            class="delete-btn p-1 text-gray-400 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                                            title="删除对话">
                                        <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
                                            <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>
                                        </svg>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 对话列表底部 -->
                <div class="border-t border-gray-200 dark:border-gray-600 p-3">
                    <button @click="loadConversationList"
                            :disabled="isLoading"
                            class="w-full px-3 py-2 text-sm bg-purple-500 text-white rounded-lg hover:bg-purple-600
                                   disabled:opacity-50 disabled:cursor-not-allowed transition-colors">
                        刷新列表
                    </button>
                </div>
            </div>
        </transition>
    </div>
</template>

<script setup>
import { ref, reactive, nextTick, onMounted, onBeforeUnmount, provide } from 'vue'
import { useRouter } from 'vue-router'
import { marked } from 'marked'
import { aiChat, deleteAiConversation, getAiChatHistory, createNewConversation, getConversationList } from '@/api/frontend/ai'
import { showMessage, showModel } from '@/composables/util'
import { getToken } from '@/composables/cookie'

const router = useRouter()

// 响应式数据
const isChatOpen = ref(false)
const inputMessage = ref('')
const isTyping = ref(false)
const isLoading = ref(false)
const conversationId = ref('')
const messagesContainer = ref(null)
const showConversationList = ref(false)
const conversationList = ref([])
const currentConversationTitle = ref('新对话')
// 组件级流式控制器
const streamController = ref(null)

// 消息列表
const messages = reactive([])

// 配置marked
marked.setOptions({
    breaks: true, // 支持换行
    gfm: true,    // 支持GitHub风格的markdown
})

// 切换聊天窗口
const toggleChat = () => {
    isChatOpen.value = !isChatOpen.value
    if (isChatOpen.value && conversationId.value) {
        // 打开时自动加载历史记录
        loadChatHistory()
    }
}

// 打开AI助手（供外部调用）
const openAiAssistant = () => {
    isChatOpen.value = true
    nextTick(() => {
        scrollToBottom()
    })
}

// 添加消息到AI助手（供外部调用）
const addMessageToAiAssistant = ({ userMessage, aiReply, conversationId: newConversationId }) => {
    // 添加用户消息
    messages.push({
        content: userMessage,
        isUser: true,
        timestamp: new Date()
    })

    // 添加AI回复
    messages.push({
        content: aiReply,
        isUser: false,
        timestamp: new Date(),
        recommendArticles: []
    })

    // 更新对话ID
    if (newConversationId) {
        conversationId.value = newConversationId
    }

    // 滚动到底部
    nextTick(() => {
        scrollToBottom()
    })
}

// 提供方法给子组件使用
provide('openAiAssistant', openAiAssistant)
provide('addMessageToAiAssistant', addMessageToAiAssistant)

// 暴露方法给父组件使用
defineExpose({
    openAiAssistant,
    addMessageToAiAssistant
})

// 渲染Markdown内容
const renderMarkdown = (content) => {
    try {
        return marked(content)
    } catch (error) {
        console.error('Markdown渲染失败:', error)
        return content.replace(/\n/g, '<br>')
    }
}

// 加载聊天历史记录
const loadChatHistory = async () => {
    if (!conversationId.value || isLoading.value) return

    isLoading.value = true
    
    try {
        const response = await getAiChatHistory({
            conversationId: conversationId.value
        })

        if (response.success) {
            const historyData = response.data
            
            // 清空当前消息
            messages.splice(0, messages.length)
            
            // 加载历史消息
            historyData.messages.forEach(msg => {
                messages.push({
                    content: msg.content,
                    isUser: msg.isUser,
                    timestamp: new Date(msg.createTime),
                    recommendArticles: msg.recommendArticles || [] // 包含历史推荐文章
                })
            })
            
            // 滚动到底部
            await nextTick()
            scrollToBottom()
            
            showMessage('历史记录加载成功', 'success')
        } else {
            showMessage('加载历史记录失败', 'error')
        }
    } catch (error) {
        console.error('加载历史记录失败:', error)
        showMessage('加载历史记录失败', 'error')
    } finally {
        isLoading.value = false
    }
}

// 发送消息
const sendMessage = async () => {
    if (!inputMessage.value.trim() || isTyping.value) return

    const userMessage = inputMessage.value.trim()

    // 添加用户消息
    messages.push({
        content: userMessage,
        isUser: true,
        timestamp: new Date()
    })

    // 清空输入框
    inputMessage.value = ''

    // 显示输入中状态
    isTyping.value = true

    // 先渲染一个占位的 AI 消息，用于流式逐字填充
    const assistantMessage = {
        content: '',
        isUser: false,
        timestamp: new Date(),
        recommendArticles: []
    }
    messages.push(assistantMessage)

    // 滚动到底部
    await nextTick()
    scrollToBottom()

    try {
        // 优先尝试流式接口（SSE over fetch）
        const token = getToken()
        streamController.value = new AbortController()
        const resp = await fetch('/api/ai/chat/stream', { signal: streamController.value.signal, 
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'text/event-stream',
                ...(token ? { 'Authorization': 'Bearer ' + token } : {})
            },
            body: JSON.stringify({
                message: userMessage,
                conversationId: conversationId.value
            })
        })

        if (!resp.ok || !resp.body) {
            throw new Error('流式接口不可用')
        }

        const reader = resp.body.getReader()
        const decoder = new TextDecoder('utf-8')
        let buffer = ''

        while (true) {
            const { value, done } = await reader.read().catch(() => ({ value: undefined, done: true }))
            if (done) break

            buffer += decoder.decode(value, { stream: true })

            // 按照 SSE 事件分隔符分割
            const events = buffer.split('\n\n')
            buffer = events.pop() || ''

            for (const evtStr of events) {
                const line = evtStr.trim()
                if (!line.startsWith('data:')) continue
                const jsonText = line.slice(5).trim()
                if (!jsonText) continue

                let evt
                try {
                    evt = JSON.parse(jsonText)
                } catch (e) {
                    continue
                }

                if (evt.error) {
                    throw new Error(evt.error)
                }

                switch (evt.type) {
                    case 'start':
                        if (evt.conversationId) {
                            conversationId.value = evt.conversationId
                        }
                        break
                    case 'chunk':
                        assistantMessage.content += evt.content || ''
                        break
                    case 'articles':
                        assistantMessage.recommendArticles = evt.articles || []
                        break
                    case 'end':
                        // 结束事件，无需额外处理
                        break
                    default:
                        // 兼容没有 type 的数据，当作 chunk
                        if (evt.content) {
                            assistantMessage.content += evt.content
                        }
                }

                await nextTick()
                scrollToBottom()
            }
        }
    } catch (error) {
        console.error('流式聊天失败，回退到非流式:', error)

        try {
            // 回退到原来的非流式接口
            const response = await aiChat({
                message: userMessage,
                conversationId: conversationId.value
            })

            if (response.success) {
                const { reply, conversationId: newConversationId, recommendArticles } = response.data
                if (newConversationId) {
                    conversationId.value = newConversationId
                }
                assistantMessage.content = reply
                assistantMessage.recommendArticles = recommendArticles || []
            } else {
                assistantMessage.content = '抱歉，我遇到了一些问题，请稍后再试。'
            }
        } catch (e2) {
            assistantMessage.content = '抱歉，网络连接出现问题，请检查网络后重试。'
        }
    } finally {
        // 隐藏输入中状态
        isTyping.value = false
        // 清理控制器
        try { if (streamController.value) { streamController.value.abort(); } } catch (e) {}
        streamController.value = null
        await nextTick()
        scrollToBottom()
    }
}

// 清空对话
const clearConversation = async () => {
    if (!conversationId.value) {
        // 如果没有对话ID，直接清空本地消息
        messages.splice(0, messages.length)
        showMessage('对话已清空', 'success')
        return
    }

    try {
        const response = await deleteAiConversation({
            conversationId: conversationId.value
        })

        if (response.success) {
            // 清空消息列表
            messages.splice(0, messages.length)
            // 重置对话ID
            conversationId.value = ''
            showMessage('对话已清空', 'success')
        } else {
            showMessage('清空对话失败', 'error')
        }
    } catch (error) {
        console.error('清空对话失败:', error)
        showMessage('清空对话失败', 'error')
    }
}

// 跳转到文章详情
const goToArticle = (articleId) => {
    router.push(`/article/${articleId}`)
    // 关闭聊天窗口
    isChatOpen.value = false
}

// 滚动到底部
const scrollToBottom = () => {
    if (messagesContainer.value) {
        messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
}

// 切换对话列表显示
const toggleConversationList = () => {
    showConversationList.value = !showConversationList.value
    if (showConversationList.value) {
        loadConversationList()
    }
}

// 开始新对话
const startNewConversation = async () => {
    if (isLoading.value) return

    isLoading.value = true

    try {
        const response = await createNewConversation({
            title: '新对话'
        })

        if (response.success) {
            const { conversationId: newConversationId, title } = response.data

            // 清空当前消息
            messages.splice(0, messages.length)

            // 设置新的对话ID和标题
            conversationId.value = newConversationId
            currentConversationTitle.value = title

            // 刷新对话列表
            if (showConversationList.value) {
                loadConversationList()
            }

            showMessage('新对话已创建', 'success')
        } else {
            showMessage('创建新对话失败', 'error')
        }
    } catch (error) {
        console.error('创建新对话失败:', error)
        showMessage('创建新对话失败', 'error')
    } finally {
        isLoading.value = false
    }
}

// 加载对话列表
const loadConversationList = async () => {
    if (isLoading.value) return

    isLoading.value = true

    try {
        const response = await getConversationList({
            pageNum: 1,
            pageSize: 20
        })

        if (response.success) {
            conversationList.value = response.data.conversations || []
        } else {
            showMessage('加载对话列表失败', 'error')
        }
    } catch (error) {
        console.error('加载对话列表失败:', error)
        showMessage('加载对话列表失败', 'error')
    } finally {
        isLoading.value = false
    }
}

// 切换对话
const switchConversation = async (conversation) => {
    if (conversation.conversationId === conversationId.value) return

    // 设置新的对话ID和标题
    conversationId.value = conversation.conversationId
    currentConversationTitle.value = conversation.title

    // 清空当前消息
    messages.splice(0, messages.length)

    // 加载对话历史
    await loadChatHistory()

    // 关闭对话列表
    showConversationList.value = false

    showMessage(`已切换到：${conversation.title}`, 'success')
}

// 删除对话确认
const deleteConversationConfirm = async (conversation) => {
    if (isLoading.value) return

    try {
        // 使用Element Plus确认对话框
        await showModel(
            `确定要删除对话"${conversation.title}"吗？此操作不可撤销。`,
            'warning',
            '删除确认'
        )

        isLoading.value = true

        const response = await deleteAiConversation({
            conversationId: conversation.conversationId
        })

        if (response.success) {
            // 如果删除的是当前对话，清空聊天界面
            if (conversation.conversationId === conversationId.value) {
                messages.splice(0, messages.length)
                conversationId.value = ''
                currentConversationTitle.value = '新对话'
            }

            // 临时重置loading状态，确保列表能够刷新
            isLoading.value = false

            // 刷新对话列表
            await loadConversationList()

            showMessage('对话已删除', 'success')
        } else {
            showMessage('删除对话失败', 'error')
        }
    } catch (error) {
        // 用户取消删除或其他错误
        if (error === 'cancel') {
            console.log('用户取消删除')
            return
        }
        console.error('删除对话失败:', error)
        showMessage('删除对话失败', 'error')
    } finally {
        isLoading.value = false
    }
}

// 格式化时间
const formatTime = (timeStr) => {
    const time = new Date(timeStr)
    const now = new Date()
    const diff = now - time

    // 小于1分钟
    if (diff < 60000) {
        return '刚刚'
    }

    // 小于1小时
    if (diff < 3600000) {
        return `${Math.floor(diff / 60000)}分钟前`
    }

    // 小于1天
    if (diff < 86400000) {
        return `${Math.floor(diff / 3600000)}小时前`
    }

    // 小于7天
    if (diff < 604800000) {
        return `${Math.floor(diff / 86400000)}天前`
    }

    // 超过7天显示具体日期
    return time.toLocaleDateString()
}

// 组件挂载时的操作
onMounted(() => {
    // 可以在这里添加一些初始化操作
})

// 组件卸载时，尽量中断可能存在的流式请求（若有）
onBeforeUnmount(() => {
    try {
        if (streamController.value) {
            streamController.value.abort()
        }
    } catch (e) {}
})
</script>

<style scoped>
/* 聊天窗口动画 */
.slide-up-enter-active,
.slide-up-leave-active {
    transition: all 0.3s ease;
}

.slide-up-enter-from {
    transform: translateY(20px);
    opacity: 0;
}

.slide-up-leave-to {
    transform: translateY(20px);
    opacity: 0;
}

/* 对话列表侧边栏动画 */
.slide-left-enter-active,
.slide-left-leave-active {
    transition: all 0.3s ease;
}

.slide-left-enter-from {
    transform: translateX(-20px);
    opacity: 0;
}

.slide-left-leave-to {
    transform: translateX(-20px);
    opacity: 0;
}

/* 对话列表项样式 */
.group:hover .group-hover\:opacity-100 {
    opacity: 1;
}

/* 删除按钮样式 */
.delete-btn {
    transition: all 0.2s ease;
}

.delete-btn:hover {
    transform: scale(1.1);
}

/* 文本截断样式 */
.line-clamp-2 {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

/* 滚动条样式 */
.overflow-y-auto::-webkit-scrollbar {
    width: 4px;
}

.overflow-y-auto::-webkit-scrollbar-track {
    background: transparent;
}

.overflow-y-auto::-webkit-scrollbar-thumb {
    background: rgba(156, 163, 175, 0.5);
    border-radius: 2px;
}

.overflow-y-auto::-webkit-scrollbar-thumb:hover {
    background: rgba(156, 163, 175, 0.8);
}

/* Markdown内容样式 */
.markdown-content {
    line-height: 1.6;
}

.markdown-content h1,
.markdown-content h2,
.markdown-content h3,
.markdown-content h4,
.markdown-content h5,
.markdown-content h6 {
    font-weight: bold;
    margin: 0.5em 0 0.3em 0;
}

.markdown-content h1 { font-size: 1.2em; }
.markdown-content h2 { font-size: 1.1em; }
.markdown-content h3 { font-size: 1.05em; }

.markdown-content p {
    margin: 0.5em 0;
}

.markdown-content ul,
.markdown-content ol {
    margin: 0.5em 0;
    padding-left: 1.5em;
}

.markdown-content li {
    margin: 0.25em 0;
}

.markdown-content code {
    background-color: rgba(175, 184, 193, 0.2);
    padding: 0.1em 0.3em;
    border-radius: 0.25em;
    font-size: 0.9em;
    font-family: 'Courier New', Courier, monospace;
}

.markdown-content pre {
    background-color: rgba(175, 184, 193, 0.1);
    padding: 0.8em;
    border-radius: 0.5em;
    overflow-x: auto;
    margin: 0.5em 0;
}

.markdown-content pre code {
    background-color: transparent;
    padding: 0;
}

.markdown-content blockquote {
    border-left: 3px solid #e2e8f0;
    padding-left: 1em;
    margin: 0.5em 0;
    color: #64748b;
}

.markdown-content strong {
    font-weight: bold;
}

.markdown-content em {
    font-style: italic;
}

/* 响应式调整 */
@media (max-width: 640px) {
    .w-96 {
        width: 90vw;
        right: 5vw;
    }

    .w-80 {
        width: 85vw;
        right: 5vw;
    }

    /* 移动端隐藏对话列表 */
    .right-96 {
        display: none;
    }
}

@media (max-width: 1024px) {
    .right-96 {
        right: 24rem;
    }

    .w-80 {
        width: 18rem;
    }
}

/* 文本截断样式 */
.line-clamp-1 {
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.line-clamp-2 {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}
</style> 